const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const $ = db.command.aggregate;
// 获取openId云函数入口函数
exports.main = async (event, context) => {
  // 返回数据库聚合结果
  let single_list = await db.collection('rates').aggregate()
      .group({
        _id: '$rateStaff',
        sum: $.sum('$rating'),
        avg: $.avg('$rating')
      })
      .sort({ sum: -1 })
      .limit(25)
      .end();
  let single_count_list = await db.collection('rates')
    .aggregate()
    .sortByCount('$rateStaff')
    .limit(25)
    .end()
  let team_list = await db.collection('rates')
      .aggregate()
      .group({
        _id: '$rateGroup',
        sum: $.sum('$rating'),
        avg: $.avg('$rating')
      })
      .sort({ sum: -1 })
      .limit(25)
      .end();
      // 插入排行榜数据库，暂定sales
      try {
       await db.collection('sales').where({
          type: 'show_rank'
        }).update({
            data:{
                single_star_list: single_list,
                team_star_list: team_list,
                single_count_list: single_count_list,
                curtime: new Date().toLocaleString()
            }
        })
      } catch (error) {
        console.log('云函数调用BUG', error)
      }
  return {single: single_list, team: team_list, count: single_count_list}
};
